<template>
  <!--养殖项目  -->
  <el-form ref="formRef" :model="dynamicValidateForm" class="demo-dynamic">
    <el-row :gutter="24">
      <el-col :span="0"></el-col>
      <el-col :span="24">
        <el-button type="text" @click.prevent="addDomain()">
          <el-icon>
            <Plus />
          </el-icon>
          <span>若有种植项目点击此处进行添加</span>
        </el-button>
      </el-col>
    </el-row>
    <el-row
      v-for="(domain, index) in dynamicValidateForm.domains"
      :gutter="24"
      :key="domain.key"
      aria-label="121"
    >
      <el-col :span="10">
        <el-form-item
          :label="'种植项目(' + (index + 1) + ')'"
          :prop="'domains.' + index + '.crop'"
          :rules="{
            required: true,
            message: '请选择种植项目！',
            trigger: 'blur',
          }"
        >
          <el-select
            v-model="domain.crop"
            placeholder="请选择种植项目"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="(item, index) in dict.type.pea_crop_pro"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="10">
        <el-form-item
          :label="'年产量（千克）'"
          :prop="'domains.' + index + '.yearOp'"
          :rules="{
            required: true,
            message: '请输入年产量！',
            trigger: 'blur',
          }"
        >
          <el-input v-model="domain.yearOp" show-word-limit maxlength="10" placeholder="请输入年产量" />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-button @click.prevent="removeDomain(domain)" style="margin-top: 30px;">
          <el-icon>
            <Minus />
          </el-icon>
        </el-button>
      </el-col>
    </el-row>

    <el-form-item>
      <el-button @click="resetForm(formRef)" v-show="dynamicValidateForm.domains.length != 0">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { cropPro } from "@/views/credit/peasants/pea-message/type";

const formRef = ref<FormInstance>();
const dynamicValidateForm = reactive<{
  domains: DomainItem[]
}>({
  domains: []
});

interface DomainItem extends cropPro {
  key: number;
  crop: string; // 养殖项目
  yearOp: string; // 年产量
}

let props = defineProps(["croping", "hzId"]);
let $emit = defineEmits(["update:croping"]);

const removeDomain = (item: DomainItem) => {
  const index = dynamicValidateForm.domains.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.domains.splice(index, 1);
  }
};

const addDomain = () => {
  dynamicValidateForm.domains.push({
    key: Date.now(),
    crop: "", // 养殖项目
    yearOp: "" // 年产量
  });
};

const subCrop = () => {
  // 创建一个 Promise 对象
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid, fields) => {
      // 进行
      if (!formRef) reject("养殖表单还有未填写字段，请填写！");
      if (valid) {
        resolve(true);
      } else {
        reject("种植表单还有未填写字段，请填写！");
      }
    });
  });
};



// const submitForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.validate((valid) => {
//     if (valid) {
//       ElMessage.success(`提交数据: ${JSON.stringify(dynamicValidateForm.domains)}`);
//       console.log("submit!", dynamicValidateForm.domains);
//     } else {
//       console.log("error submit!");
//       return false;
//     }
//   });
// };

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dynamicValidateForm.domains.forEach((item) => {
    item['crop'] = "";
    item['yearOp'] = "";
  })
  $emit("update:croping", dynamicValidateForm.domains);
};

/*数据的绑定*/
watch(
  () => props.hzId,
  () => {
    if (props.hzId == "") {
      dynamicValidateForm.domains = []
      addDomain();
    } else {
      dynamicValidateForm.domains = [...props.croping];
    }
  }
);


watch(
  () => dynamicValidateForm.domains,
  () => {
    $emit("update:croping", dynamicValidateForm.domains);
  }
);

// update:farmPros
onMounted(() => {
  if(props.hzId == ""){
    dynamicValidateForm.domains = [];
    addDomain();
  }else {
    dynamicValidateForm.domains = [...props.croping];
  }
});


// 清空
const removeAll = () => {
  dynamicValidateForm.domains = [];
  $emit("update:croping", dynamicValidateForm.domains)
}

const subFarm = () => {
  // 创建一个 Promise 对象
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid, fields) => {
      // 进行
      if (!formRef) reject("养殖表单还有未填写字段，请填写！");
      if (valid) {
        resolve(true);
      } else {
        reject("养殖表单还有未填写字段，请填写！");
      }
    });
  });
};


defineExpose({
  subCrop,
  removeAll
});
</script>

<script lang="ts">
export default {
  dicts: ["pea_crop_pro"]
};
</script>

<style lang="scss" scoped></style>
